<template>
  <div class="home">
    <!--<header>
          <div class="header-left"></div>
          <router-link class="header-right" to="/status" tag="div" v-if="userGroupRole==4">登陆/注册</router-link>
          <div v-else @mouseenter="showUserInfo=true" @mouseleave="showUserInfo=false" class="user-info">
            <van-button type="primary" class="vant-userInfo">
              {{this.$store.getters.nick}}
              <van-icon style="vertical-align: middle" name="arrow-down"/>
            </van-button>

            <div class="userInfo" v-if="showUserInfo">
              <router-link to="/userdata" tag="div">个人资料</router-link>
              <router-link to="/useredit" tag="div">编辑资料</router-link>
              <div @click="logOut">退出登录</div>
            </div>
          </div>
        </header>-->
    <!--<van-tabs class="" style="height:93%" v-model="active" type="card" background="#241224" color="#413241" animated>
          <van-tab title="聊天">-->
    <van-notice-bar color="#1989fa" background="#ecf9ff">{{announcement}}</van-notice-bar>
    <div class="msgcontainer" @click="fixScroll()">
      <vue-scroll :ops="ops" @handle-resize="handleResize" @handle-scroll="handleScroll"
                  @handle-scroll-complete="handleComplete" ref="vs">
        <div class="msgbox" v-for="(item,index) in allMsgArr" :key="index">
          <div v-if="item.isBroadcast">
            <div style="margin:0 auto;color: #d83624;" class="layim_chatsay1"
                 v-html="item.content.replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, emotion)"></div>
          </div>
          <div v-else>
            <div style="text-align: left">
              <img :src="item.userImg" alt class="userImg"/>
              <div class="user-text">
                <span>{{item.name}}</span>
                <span>{{item.times|format}}</span>
              </div>
            </div>
            <!--                文本-->
            <div class="layim_chatsay bubble" :class="{'cor':userGroupRole==2}"
                 v-html="item.msg.replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, emotion)" v-if="item.type==0"></div>
            <!--                图片-->
            <div v-else-if="item.type==1" class="userInfo-img bubble" v-viewer="{toolbar:false,zoomable:false}">
              <img :src="item.msg"/>
            </div>
            <!--                  红包-->
            <div class="redpacket bubble" v-else-if="item.type==6">
              <div class="redpacketbox" :data-redid="item.msg[0]" @click.stop="grabRedPacket($event)">
                <img src="../assets/img/hongbao.png" :data-redid="item.msg[0]" @click.stop="grabRedPacket($event)"/>
                <span :data-redid="item.msg[0]" @click.stop="grabRedPacket($event)">{{item.msg[1]}}</span>
              </div>
            </div>
          </div>
        </div>
      </vue-scroll>
    </div>
    <footer class="footer" id="apply">
      <i class="iconfont icon-biaoqing" @click.stop="showEmotion=true"></i>
      <textarea id="sendTextarea" class="messageEditor" placeholder="请输入内容" v-model="content" v-paste="handlePaste"
                v-on:keyup.enter="sendMsg"></textarea>
      <van-button class="sendMsg" type="warning" size="small" @click="sendMsg">发送</van-button>
      <van-icon class="vantadd" @click="show=true" name="add-o"/>
    </footer>
    <!--  </van-tab>
          <van-tab title="客服">
            <div class="chatwithcustomer">
              <img src="../assets/img/kefu.png" alt/>
              <span class="customertext">红包提现客服QQ:1491356434</span>
              <a class="btn-qq nocustomer" href="http://wpa.qq.com/msgrd?v=3&amp;uin=1491356434&amp;site=qq&amp;menu=yes"
                 target="_blank">
                <i class="iconfont icon-qq"></i>QQ交谈
              </a>
            </div>
            <div class="chatwithcustomer">
              <img src="../assets/img/kefu.png" alt/>
              <span class="customertext">VIP兑换客服QQ：1492146118</span>
              <a class="btn-qq nocustomer" href="http://wpa.qq.com/msgrd?v=3&amp;uin=1491356434&amp;site=qq&amp;menu=yes"
                 target="_blank">
                <i class="iconfont icon-qq"></i>QQ交谈
              </a>
            </div>
            <div class="chatwithcustomer">
              <img src="../assets/img/kefu.png" alt/>
              <span class="customertext">聊天室客服QQ：1501895123</span>
              <a class="btn-qq nocustomer" href="http://wpa.qq.com/msgrd?v=3&amp;uin=1491356434&amp;site=qq&amp;menu=yes"
                 target="_blank">
                <i class="iconfont icon-qq"></i>QQ交谈
              </a>
            </div>
            <div class="chatwithcustomer">
              <img src="../assets/img/kefu.png" alt/>
              <span class="customertext">PILIPILI客服：3035111888</span>
              <a class="btn-qq nocustomer" href="http://wpa.qq.com/msgrd?v=3&amp;uin=1491356434&amp;site=qq&amp;menu=yes"
                 target="_blank">
                <i class="iconfont icon-qq"></i>QQ交谈
              </a>
            </div>
          </van-tab>
          <van-tab title="棋牌下载" url="http://aaq19.cn/" target="_blank"></van-tab>
          <van-tab title="午夜片下载" url="http://pili520.cn/index.html" target="_blank"></van-tab>
        </van-tabs>-->

    <div class="redbox" v-if="redshow">
      <i class="iconfont icon-htmal5icon19 red-close" @click="redclose"></i>
      <van-cell-group>
        <van-field class="redInput" v-model.trim="redmoney" required label="红包金额"/>
        <van-field class="redInput" v-model.trim="redcount" label="红包个数" required/>
        <van-field class="redInput" v-model.trim="redmsg" label="红包留言"/>
      </van-cell-group>
      <van-button type="info" @click="sendRedPacket" style="transform: translateX(-100%)">发送</van-button>
    </div>
    <div class="redDetail" v-if="redDetailshow">
      <i class="iconfont icon-htmal5icon19 redDetailClose" @click="closeredDetail"></i>
      <img :src="redSendPeoplePic ? redSendPeoplePic : require('@/assets/img/null.jpg')" alt/>
      <em>{{redSendPeople}} 的红包</em>
      <span>{{openMessage}}</span>
      <p class="baginformation">已领取{{redLast}}/{{redSum}}个，共{{redTotalAmount}}元</p>
      <ul>
        <li v-for="item in getRedUserList" :key="item.getUserid">
          <div class="leftinfo">
            <img :src="item.getUserIcon ? item.getUserIcon : require('@/assets/img/null.jpg')" class="userredimg"/>
            <div>
              <i>{{item.getUsername}}</i>
              <i style="font-size: 12px;color: #a0a0a0">{{item.getTime}}</i>
            </div>
          </div>
          <div class="rightinfo">
            <div>
              <i>{{item.getMoney}}元</i>
              <i style="font-size: 12px;color: #8B0000" v-if="item.isbest">手气最佳</i>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="failred" v-if="redOpenshow">
      <i class="iconfont icon-htmal5icon19 redDetailClose" @click="closeredOpen"></i>
      <img :src="redSendPeoplePic ? redSendPeoplePic : require('@/assets/img/null.jpg')" alt/>
      <p>{{redSendPeople}} 的红包</p>
      <p>{{openMessage}}</p>
      <span @click="lookOther">看看大家的手气>></span>
    </div>

    <!--    表情组件-->
    <emotion class="emcontainer" @emotion="handleEmotion" v-if="showEmotion"></emotion>
    <!--        底部弹出层-->
    <van-popup v-model="show" position="bottom">
      <!--<div class="icon-container" @click="sendBanned" v-if="userGroupRole==2">
            <van-icon name="iconfont icon-icon--" id="bannedicon"/>
      </div>-->
      <div class="icon-container">
        <van-icon name="photo-o"/>
        <input type="file" multiple accept="image/*" id="chat_file" @change="uploadAvatar"/>
      </div>
      <div class="icon-container" @click="redshow=true" v-if="userGroupRole==2">
        <van-icon name="gold-coin-o"/>
      </div>
      <div class="icon-container" @click="sendBanned" v-if="userGroupRole==2">
        <van-icon><i :class="bannedIcon"></i></van-icon>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import Emotion from "./Emotion";
  import {uploadImg, sendRedPacket, grabRedPacket, showRedPacketDetail, getAnnounce} from "../api";

  export default {
    name: "home",
    components: {
      Emotion
    },
    data() {
      return {
        //ws心跳包
        heartCheck: {
          that: this,
          timeout: 60000,
          timeoutObj: null,
          reset: function () {
            clearTimeout(this.timeoutObj);
            this.start();
          },
          start: function () {
            this.timeoutObj = setTimeout(() => {
              this.that.ws.send(JSON.stringify({cmd: 13}));
            }, this.timeout);
          }
        },
        ops: {
          bar: {
            background: "#fff",
            minSize: 0,
            opacity: 0.3,
            size: "4px"
          },
          vuescroll: {
            detectResize: true,
            mode: "native",
            sizeStrategy: "percent"
          },
          scrollPanel: {
            scrollingX: false,
            scrollingY: true,
            initialScrollY: "100%"
          }
        },
        ws: null,
        // selfNick:"",
        active: 0,
        content: "",
        showUserInfo: false,
        showEmotion: false,
        show: false,
        allMsgArr: [],
        userId: "",  // 用户id
        account: "", // 用户账号
        nick: "",
        groupId: 1, // 聊天室群组
        userGroupRole: "", // 1:群主 2:管理员 3:成员 4:游客
        bannedInd: "", // 是否禁言 1：禁言、0：取消禁言
        bannedIcon: "", // 禁言图标
        // bannedHint: '', // 禁言提示
        redshow: false,
        redDetailshow: false,
        redOpenshow: false,
        openMessage: '',
        getRedUserList: [],
        redid: "",
        thisredid: "",
        redmoney: "",
        redSendPeople: "",
        redSendPeoplePic: "",
        redcount: "",
        redmsg: "恭喜发财",
        redTotalAmount: "",
        redSum: "",
        redLast: "",
        //广播轮播
        slideTimer: "",
        announcements: [],
        announcement:
          "_________________________________________________________________________________________", // 默认公告字符太少则内容不滚动
        slideshowIndex: 0,
        start: -1
      };
    },
    methods: {
      // 获取ws地址
      getWsUrl(token, group) {
        // const token = sessionStorage.getItem("token") || "";
        const url = `ws://47.56.231.11:3333?token=${token}&groupid=${group}`;
        console.log("url:", url);
        return url;
      },

      fixScroll() {
        let u = navigator.userAgent;
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isiOS) {
          window.scrollTo(0, 0);
        }

      },
      //获取左侧用户列表
      // getUserList() {
      //   const userPar = {
      //     cmd: 17,
      //     type: 0,
      //     group_id: this.groupId
      //   };
      //   this.ws.send(JSON.stringify(userPar));
      // },

      //处理ws返回的消息
      dealMsg() {
        this.ws.onmessage = e => {
          this.heartCheck.reset();
          let newMessage = JSON.parse(e.data);
          //用户上线
          if (newMessage.command === 6) {
            if (newMessage.code === 10007) {
              // this.selfNick = newMessage.user.nick
              this.userId = newMessage.user.id;
              this.account = newMessage.user.account
              this.nick = newMessage.user.nick;
              if (newMessage.user.userType === 2) { // 用户类型  0:游客   1:会员   2:管理员
                this.userGroupRole = 2
              } else if (newMessage.user.userType === 1) {
                this.userGroupRole = 3
              } else {
                this.userGroupRole = 4
              }
              sessionStorage.setItem("nick", newMessage.user.nick);
              this.bannedState() // 获取群禁言状态
            }
          }
          // 用户加入群组
          if (newMessage.command === 8) {
            // this.getUserList();
            // this.showUserOnline(newMessage.data.user.nick)
          }
          //用户下线
          if (newMessage.command === 10) {
          }
          //用户在线列表
          if (newMessage.command === 18) {
            // this.$store.commit('handleUserList', this.groupUserList)
            // this.groupManagers = newMessage.data.groups[0].manager;
          }

          //历史消息
          if (newMessage.command === 20) {
            const msg = newMessage.data.groups[this.groupId];
            if (msg) {
              msg.forEach((item) => {
                item.type = item.msgType;
                item.times = item.createTime;
                if (item.extras.fromAvatar) {
                  item.userImg = item.extras.fromAvatar;
                } else {
                  item.userImg = require("@/assets/img/null.jpg");
                }
                item.msg = item.msgType === 6 ? item.content.split("-") : item.content;
                item.name = item.extras.fromNick;
                this.allMsgArr.unshift(item);
                // this.handleResize();
              })
            }
          }

          // (系统)广播消息
          if (newMessage.command === 50) {
            // console.log(newMessage)
            let newMsg = {}
            newMsg.isBroadcast = true
            newMsg.content = newMessage.data.content
            this.allMsgArr.push(newMsg)
          }
          // 一般聊天消息
          if (newMessage.command === 11) {
            // 过滤游客或一般成员(非群组管理员)自己发送的一般群聊消息
            // if (this.userGroupRole !== 2 && newMessage.data.from === this.userId && newMessage.data.group_id) {
            //   return false;
            // }
            this.operNewmessage(newMessage);
          }
          // 群聊审核响应消息
          if (newMessage.command === 41) {
            // 显示用户自己发送的审核消息，其他则不显示
            if (newMessage.data.from === this.userId) {
              this.operNewmessage(newMessage);
            }
          }
          // 群聊禁言状态
          if (newMessage.command === 22) {
            this.bannedInd = newMessage.data.bannedInd;
            this.showBanned();
          }
          // 用户信息更新响应
          if (newMessage.command === 39) {
            // console.log('---用户信息更新响应---')
            // console.log(newMessage)
          }
        };
      },
      operNewmessage(newMsg) {
        switch (newMsg.data.msgType) {
          //文本
          case 0:
            this.putNewmessage(newMsg);
            break;
          //图片
          case 1:
            this.putNewmessage(newMsg);
            break;
          //红包
          case 6:
            newMsg.data.content = newMsg.data.content.split("-");
            this.putNewmessage(newMsg);
            break;
          //视频
          case 3:
            break;
          //音乐
          case 4:
            break;
          default:
            break;
        }
      },
      putNewmessage(newMsg) {
        newMsg.type = newMsg.data.msgType;
        newMsg.times = newMsg.data.createTime;
        if (newMsg.data.extras.fromAvatar) {
          newMsg.userImg = newMsg.data.extras.fromAvatar;
        } else {
          newMsg.userImg = require("@/assets/img/null.jpg");
        }
        newMsg.name = newMsg.data.extras.fromNick;
        newMsg.msg = newMsg.data.content;
        this.allMsgArr.push(newMsg);
      },
      //获取历史消息记录
      getHistoryMsg() {
        if (this.ws === null) {
          return false
        }
        if (this.start > this.allMsgArr.length - 1) {
          return false
        }
        const historyPar = {
          cmd: 19,
          groupId: this.groupId,
          userId: this.userId,
          type: 1,
          start: this.start + 1,
          end: this.start += 20
        };
        this.ws.send(JSON.stringify(historyPar));
        this.offset += 20;
      },

      getAnnouncement() {
        getAnnounce("0").then(res => {
          if (res.data.code === 0 && res.data.data !== null) {
            let index = 0;
            res.data.data.forEach(item => {
              this.announcements[index] = item.content;
              index++;
            });
            if (
              this.announcements !== undefined &&
              this.announcements.length > 0
            ) {
              this.announcement = this.announcements[this.slideshowIndex];
            }
            this.slideshowIndex++;
            this.slideTimer = setInterval(this.setAnnounce, 50000); // 开始轮播
          }
        });
      },
      setAnnounce() {
        if (this.announcements !== undefined && this.announcements.length > 0) {
          this.announcement = this.announcements[this.slideshowIndex];
          this.slideshowIndex++;
          if (this.slideshowIndex >= this.announcements.length) {
            this.slideshowIndex = 0;
          }
        }
      },

      handleEmotion(i) {
        this.content += i;
      },
      // 将匹配结果替换表情图片
      emotion(res) {
        let word = res.replace(/\#|\;/gi, "");
        const list = ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '大兵', '奋斗', '咒骂', '疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '挥手', '激动', '街舞', '献吻', '左太极', '右太极'];
        let index = list.indexOf(word);
        return `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif" style="vertical-align: middle">`;
      },

      //发送消息
      sendMsg() {

        if (this.bannedInd === 1 && this.userGroupRole !== 2) {
          // 群禁言状态下非群主或管理员不能发送群消息
          // this.showBanned();
          return false;
        }
        const par = {
          // cmd: this.userGroupRole === 2 ? 11 : 40,
          cmd: 11,
          from: this.userId,
          msgType: 0,
          chatType: 1,
          group_id: this.groupId,
          content: this.content
        };
        if (this.content.length !== 0) {
          this.ws.send(JSON.stringify(par));
          this.content = "";
        }
        this.fixScroll();
      },

      //发送红包
      sendRedPacket() {
        const par = {
          userId: this.userId,
          type: 2,
          content: this.redmsg,
          totalNum: this.redcount,
          money: this.redmoney
        };
        if (this.redmoney.length !== 0 && this.redcount > 0 && this.redmsg.length !== 0) {
          sendRedPacket(par).then(res => {
            if (res.data.code === 0) {
              this.redid = res.data.data;
              this.redshow = false;
              const params = {
                // cmd: this.userGroupRole === 2 ? 11 : 40,
                cmd: 11,
                msgType: 6,
                chatType: 1,
                group_id: this.groupId,
                content: `${this.redid}-${this.redmsg}`
              };
              this.ws.send(JSON.stringify(params));
            } else {
              window.alert(res.data.message);
            }
          });
        } else {
          window.alert("发送失败");
        }
      },

      //抢红包
      grabRedPacket(e) {
        this.thisredid = e.target.dataset.redid;
        const par = {
          id: e.target.dataset.redid,
          userId: this.userId
        };
        if (this.userGroupRole !== 4) {
          grabRedPacket(par).then(res => {
            this.redOpenshow = true;
            this.redTotalAmount = res.data.data.sendMoney;
            this.redSum = res.data.data.redPacketCount;
            this.redSendPeople = res.data.data.sendPacketUser;
            this.redSendPeoplePic = res.data.data.profilePicture;
            switch (res.data.code) {
              case 0: // 显示红包详情
                if (0 === res.data.data.money){
                  this.openMessage = '';
                }else {
                  this.openMessage = '得到 ' + res.data.data.money + ' 元';
                }
                break;
              case -1: // 手慢了,红包派完了
                this.openMessage = '手慢了,红包派完了';
                break;
              case -2: // 该红包已过期
                this.openMessage = '该红包已过期';
                break;
              case -3: // 您已经抢过该红包
                this.openMessage = '您已经抢过该红包';
                break;
              default:
                break;
            }
          });
        } else {
          window.alert("请登陆后尝试");
        }
      },

      //红包详情
      showRedPacketDetail(id) {
        showRedPacketDetail(id).then(res => {
          console.log('showRedPacketDetail...', res.data.data);
          this.getRedUserList = res.data.data;
          this.redLast = res.data.data.length;
        });
      },

      lookOther() {
        this.redOpenshow = false;
        this.redDetailshow = true;
        this.showRedPacketDetail(this.thisredid);
      },

      handleResize(vertical) {
        this.$refs.vs.scrollTo({y: "100%"}, 100);
      },

      handleScroll() {
        if (this.$refs["vs"].getScrollProcess().v < 0.9) {
          this.ops.vuescroll.detectResize = false;
        } else {
          this.ops.vuescroll.detectResize = true;
        }

        if (this.$refs["vs"].getScrollProcess().v == 0) {
          this.getHistoryMsg();
        }
      },

      handleComplete() {
        this.ops.vuescroll.detectResize = true;
      },

      logOut() {
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("account");
        sessionStorage.removeItem("LoginFlag");
        this.$store.commit("handleAccountName", "");
        this.$store.state.LoginFlag = true;
        this.showUserInfo = false;
        window.location.reload();
      },

      logOut1() {
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("account");
        sessionStorage.removeItem("LoginFlag");
        this.$store.commit("handleAccountName", "");
        this.$store.state.LoginFlag = true;
        this.showUserInfo = false;
      },

      toggleEmotion() {
        this.showEmotion = false;
      },
      //图片上传
      uploadAvatar(input) {
        let file = input.target.files[0];
        if (!file) {
          return;
        }
        if (typeof FileReader === "undefined") {
          window.alert("浏览器版本过低!");
          return;
        } else if (!/image\/\w+/.test(file.type)) {
          window.alert("必须上传图片");
          return;
        }
        if (file.size <= 500 * 1024) {
          this.upload(file);
          return;
        }
        const reader = new FileReader();
        const _this = this;
        reader.onload = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          img.onload = function () {
            const file = _this.compress(img);
            const bytes = window.atob(file.split(",")[1]);
            let array = [];
            for (let i = 0; i < bytes.length; i++) {
              array.push(bytes.charCodeAt(i));
            }
            let blob = new Blob([new Uint8Array(array)], {
              type: "image/jpeg"
            });
            _this.upload(blob);
          };
        };
        reader.readAsDataURL(file);
      },

      // 上传图片
      upload(file) {
        let data = new FormData();
        data.append("file", file, file.name);
        uploadImg(data).then(res => {
          if (res.status === 200) {
            if (document.getElementById("chat_file")) {
              document.getElementById("chat_file").value = "";
            }
            const params = {
              // cmd: this.userGroupRole === 2 ? 11 : 40,
              cmd: 11,
              from: this.userId,
              msgType: 1,
              chatType: 1,
              group_id: this.groupId,
              content: res.data.msg
            };
            this.ws.send(JSON.stringify(params));
            this.show = false;
          }
        });
      },

      // 压缩图片
      compress(img) {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        // 图片原始尺寸
        let originWidth = img.width;
        let originHeight = img.height;
        // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
        let maxWidth = 400,
          maxHeight = 400;
        // 目标尺寸
        let targetWidth = originWidth,
          targetHeight = originHeight;
        // 图片尺寸超过300x300的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }
        }
        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight);
        let newUrl = canvas.toDataURL("image/jpeg", 0.5); //base64 格式
        return newUrl;
      },
      sendBanned() { // 管理员发送禁言指令/取消禁言指令
        const params = {
          cmd: 21,
          from: this.userId,
          group_id: this.groupId,
          bannedInd: this.bannedInd === 1 ? 0 : 1, // 1:禁言、0：取消禁言
        }
        this.ws.send(JSON.stringify(params))
      },
      showBanned() {
        if (this.bannedInd === 1) {
          document.getElementById("sendTextarea").placeholder = "当前群禁言状态";
        } else {
          document.getElementById("sendTextarea").placeholder = "请输入内容";
        }
      },
      bannedState() {
        // 成员请求当前群组是否禁言的状态
        // console.log('----成员请求当前群组是否禁言的状态----')
        const params = {
          cmd: 46,
          from: this.userId,
          group_id: this.groupId
        };
        this.ws.send(JSON.stringify(params));
      },
      setBannedState() {
        if (this.bannedInd === 1) {
          this.bannedIcon = "iconfont icon-icon--";
          // this.bannedHint = '关闭禁言'
        } else {
          this.bannedIcon = "iconfont icon-yuyin";
          // this.bannedHint = '开启禁言'
        }
      },
      redclose() {
        this.redshow = false;
      },
      closeredDetail() {
        this.redDetailshow = false;
      },
      closeredOpen() {
        this.redOpenshow = false;
      },
      ws_send(params) {
        // console.log('-----ws_send-----')
        this.ws.send(params)
      },
      //微信截图上传图片时触发
      handlePaste(e) {
        let file = null
        if (e.clipboardData && e.clipboardData.items[0] && e.clipboardData.items[0].type && e.clipboardData.items[0].type.indexOf('image') > -1) { //这里就是判断是否有粘贴进来的文件且文件为图片格式
          file = e.clipboardData.items[0].getAsFile();
        } else {
          this.$message({
            type: 'warning',
            message: '上传的文件必须为图片且无法复制本地图片且无法同时复制多张图片'
          })
          return;
        }
        this.upload(file)
      },

    },
    mounted() {
      var that = this;
      Event.$on('ws_send', function (params) {
        that.ws_send(params)
      })
    },
    created() {
      const token = this.$route.query.token, group = this.$route.query.group;
      // this.userId = userid;
      this.groupId = (group) ? group : "0";
      // console.log("token::", token);
      // console.log("group:", this.groupId);
      this.ws = new WebSocket(this.getWsUrl(token, group));
      this.ws.onopen = () => {
        console.log("open");
        this.heartCheck.start();
        this.dealMsg();
        // this.getHistoryMsg()
      };

      this.ws.onclose = () => {
        this.logOut1();
        console.log("close");
      };

      this.ws.onerror = () => {
        this.logOut1();
        console.log("error");
      };
      this.globalClick(this.toggleEmotion);
      // this.slideTimer = setInterval(this.getAnnouncement, 50000); // 开始轮播 setAnnounce
      this.getAnnouncement(); //  获取公告内容并开始轮播

      var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      window.onresize = function () {
        var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        if (clientHeight - nowClientHeight > 60) {
          //因为ios有自带的底部高度
          //键盘弹出的事件处理
          document.getElementById("apply").classList.add("focusState");
        } else {
          //键盘收起的事件处理
          document.getElementById("apply").classList.remove("focusState");
        }
      };
    },
    watch: {
      userId: "getHistoryMsg",
      bannedInd: 'setBannedState',
      immediate: true
    },
    directives: {
      'paste': {
        bind(el, binding, vnode) {
          el.addEventListener('paste', function (event) { //这里直接监听元素的粘贴事件
            binding.value(event)
          })
        }
      } //复制粘贴指令
    },
    filters: {
      //格式化时间
      format(dateStr, pattern = "") {
        let dt = new Date(dateStr);
        //   yyyy-mm-dd
        let y = dt.getFullYear();
        let m =
          dt.getMonth() + 1 >= 10 ? dt.getMonth() + 1 : `0${dt.getMonth() + 1}`;
        let d = dt.getDate() >= 10 ? dt.getDate() : `0${dt.getDate()}`;
        if (pattern.toLowerCase() == "yyyy-mm-dd") {
          return `${y}-${m}-${d}`;
        } else {
          let hh = dt.getHours() >= 10 ? dt.getHours() : `0${dt.getHours()}`;
          let mm = dt.getMinutes() >= 10 ? dt.getMinutes() : `0${dt.getMinutes()}`;
          let ss = dt.getSeconds() >= 10 ? dt.getSeconds() : `0${dt.getSeconds()}`;
          return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
        }
      }
    }
  };
</script>

<style scoped lang="less">
  .home {
    width: 100%;
    height: 100%;

    header {
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 7%;
      width: 100%;
      background: linear-gradient(top, #222, #413241);

      .header-left {
        display: inline-block;
        height: 100%;
        width: 70%;
        background: url("../assets/img/iconbg.png") left center no-repeat;
        background-size: 60%;
      }

      .header-right {
        width: 30%;
        color: #fff;
        font-size: 18px;
        font-weight: 600;
      }

      .user-info {
        width: 30%;
        text-align: right;
        padding-right: 15px;

        button {
          padding: 0;
        }
      }

      .userInfo {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        width: 90px;
        height: 60px;
        position: absolute;
        right: 4px;
        background-color: #fff;
        font-size: 14px;
        z-index: 99999;
        border-radius: 6px;
        padding: 8px 0;

        > div {
          cursor: pointer;
        }
      }
    }

    .emcontainer {
      position: absolute;
      bottom: 51px;
    }

    .icon-container {
      display: inline-block;
      border: 1px solid #dcdcdc;
      border-radius: 12px;
      height: 56px;
      width: 56px;
      text-align: center;
      margin: 20px 0 20px 20px;

      i {
        font-size: 34px;
        margin-top: 10px;
      }

      #chat_file {
        opacity: 0;
        position: absolute;
        width: 62px;
        height: 61px;
        top: 17px;
        left: 19px;
      }
    }

    .chatwithcustomer {
      display: flex;
      margin-top: 13px;
      justify-content: space-around;
      align-items: center;
      font-size: 16px;

      img {
        border-radius: 50%;
        vertical-align: middle;
        width: 10%;
      }

      .customertext {
        width: 50%;
        font-size: 15px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .btn-qq {
        background-color: #fdc965;
        color: #fff;
        padding: 4px 6px;
        border-radius: 4px;

        i {
          padding-right: 10px;
        }
      }
    }

    .msgcontainer {
      height: 88%;
      background-color: #e4e3e3;

      .msgbox {
        position: relative;
        margin: 20px 10px;
        max-width: 300px;

        .userImg {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          vertical-align: text-top;
        }

        .user-text {
          display: inline-block;
          color: #635a5a;
          padding-left: 5px;
          font-size: 14px;
        }

        .bubble {
          &:before {
            content: "";
            height: 0;
            width: 0;
            position: absolute;
            top: 0;
            left: -8px;
            border-left: 8px solid transparent;
            border-right: 8px solid transparent;
            border-top: 8px solid #fff;
          }
        }

        .layim_chatsay {
          position: relative;
          left: 18%;
          top: -7px;
          word-wrap: break-word;
          word-break: break-all;
          padding: 6px 11px;
          background-color: #ffffff;
          border-radius: 7px;
          font-size: 14px;
          width: fit-content;
          min-width: 20px;
          // display: flex;
          text-align: left;
          white-space: pre-wrap;
        }

        .layim_chatsay1 {
          position: relative;
          word-wrap: break-word;
          word-break: break-all;
          padding: 5px 11px;
          background-color: #ffffff;
          border-radius: 3px;
          font-size: 14px;
          width: fit-content;
          min-width: 20px;
          text-align: center;
        }

        .userInfo-img {
          position: relative;
          left: 17%;
          top: 55%;
          padding: 10px;
          margin-top: -10px;
          width: fit-content;
          background-color: #fff;
          border-radius: 7px;

          &:before {
            content: "";
            height: 0;
            width: 0;
            position: absolute;
            top: 0;
            left: -8px;
            border-left: 8px solid transparent;
            border-right: 8px solid transparent;
            border-top: 8px solid #fff;
          }

          img {
            display: flex;
            max-width: 180px;
            height: auto;
          }
        }

        .redpacket {
          position: relative;
          left: 18%;
          top: -7px;
          padding: 10px;
          background-color: #fff;
          width: 280px;
          height: 170px;
          border-radius: 3px;

          .redpacketbox {
            display: flex;
            align-items: center;
            width: 100%;
            height: 100%;
            justify-content: space-around;
            background-color: #fa9d3b;
            border-radius: 4px;

            img {
              flex: 2;
              vertical-align: middle;
            }

            span {
              flex: 1;
              color: #f30;
              font-size: 14px;
              font-weight: 900;
              text-overflow: ellipsis;
            }
          }
        }
      }
    }

    .footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      height: 50px;
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .icon-biaoqing,
      .vantadd {
        font-size: 30px;
        margin: 0 7px;
      }

      .messageEditor {
        border: 1px solid #cbcbcb;
        border-radius: 5px;
        padding: 3px 7px;
        flex: 4;
        margin-right: 11px;
        margin-left: 4px;
        max-height: 40px;
        font-size: 14px;
        resize: none;
      }
    }

    .redbox {
      width: 300px;
      height: 250px;
      border-radius: 4px;
      background-color: #fff;
      position: fixed;
      left: 10%;
      top: 29%;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      align-items: center;

      span {
        font-size: 14px;
        margin-right: 10px;
      }

      .red-close {
        position: absolute;
        right: -4px;
        top: -8px;
        font-size: 24px;
      }
    }

    .redDetail {
      position: fixed;
      left: 4%;
      top: 21%;
      width: 347px;
      height: 400px;
      border-radius: 8px;
      text-align: center;
      background: url("../assets/img/successredbag.png") no-repeat;
      background-size: cover;

      .baginformation {
        height: 16px;
        font-size: 12px;
        text-align: center;
        color: #000;
        background-color: #f0f0f0;
      }

      img {
        width: 60px;
        height: 60px;
        margin-top: 50px;
        box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.5);
        border-radius: 50%;
      }

      em {
        display: block;
        font-size: 24px;
        margin: 13px 0;
      }

      span {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: #fc4c4c;
      }

      ul {
        height: 207px;
        background-color: #fff;
        overflow-y: auto;
        border-radius: 4px;

        li {
          box-sizing: border-box;
          width: 100%;
          height: 70px;
          padding: 0 13px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .leftinfo {
            display: flex;
            align-items: center;

            > div {
              display: flex;
              text-align: left;
              padding-left: 9px;
              flex-direction: column;
            }
          }

          .rightinfo {
            display: flex;
            align-items: center;

            > div {
              display: flex;
              text-align: right;
              padding-left: 9px;
              flex-direction: column;
            }
          }

          .userredimg {
            width: 40px;
            height: 40px;
            margin-top: 0;
            vertical-align: middle;
          }

          i,
          div {
            font-size: 20px;
          }
        }
      }
    }

    .failred {
      position: fixed;
      left: 8%;
      top: 20%;
      text-align: center;
      width: 314px;
      height: 414px;
      background: url("../assets/img/meetredbag.png") no-repeat;
      background-size: cover;

      img {
        width: 60px;
        height: 60px;
        margin-top: 50px;
        box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.5);
        border-radius: 50%;
      }

      p {
        font-size: 24px;
        color: #fff;
        margin: 20px 0;
      }

      span {
        display: inline-block;
        cursor: pointer;
        margin-top: 135px;
        font-size: 14px;
        color: #fa9d3b;
      }
    }

    .redDetailClose {
      position: absolute;
      right: -4px;
      top: -6px;
      color: #fff;
      font-size: 24px;
    }

    .redInput {
      line-height: 25px !important;
    }

    [v-cloak] {
      display: none;
    }
  }

  .focusState {
    position: absolute;
  }

  .cor {
    color: #12a912;
  }
</style>
